from alipay import AliPay


# 支付宝公钥，用于验证支付回调签名
alipay_public_key_string = """-----BEGIN PUBLIC KEY-----

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsky++f5jewSG1238TJLjMsVSqCs9/IhRtEQxdeNW6njmmHS8DsWyo4txFEyn8pWt8nfmTQtGcsZz3zgt8fUwDBncoim/sX0Sakqm2QIPGuzRu+714F6wduhiHNR+9kpkiPZ6XSj2xOW0KHea1BklHfiONzkG4wdk2bdQ55GEKneaQlVDc3iO3mOPQnFlrMN7Xlb/TWbRaU/eeGGUAXwJb0M0J1KcPl7FpvLTavDqQejatEdgB9jB4nzAE9/KLgFYg89hcPWTTh0K4IUboEQVPh7wQpb36mlB+9XIY1q8EBgGXPtE/3XeNZHhalU5ML9MfhLyOexF9SdwhiJT3OlZ8wIDAQAB
-----END PUBLIC KEY-----"""
# 应用私钥，用于生成支付签名，我们需要转换私钥格式
# https://opendocs.alipay.com/common/02khjp?pathHash=e5a2e515
app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----

MIIEowIBAAKCAQEAp0hStdax/lG9+IjVLXxmWZdxi1pUrYmAGHwqGcGr2qyvDN0Z1X6HnFVUACNmIOjc8D5zWuCiO/lLqRsj4dno+wEHl5u1vlEu2DJC7NecMGDvOrodhLoJiNzdTl3utXl6geR2lCBgaJqUEtRyaV55TV2CWTdaL7S3BuYFDX/S6snVzNU2V+njDuIpOZ4aesexzjXZSBoohO8PsEQ+nC09NWt0hp46M7a/D3A58UWYfzMC6dejVCeoqoM3t4AbSKcbB69OsgAv9HEPa21SvNnlezQCPL1mR6PQxoNBxIxmqgGypx/J6EfA5HNIwH+ZDRz+weWMR0QP+O+o7qVBg4aIZQIDAQABAoIBAE9y5AWFAGh/PjCKHGVMDfhDGyRKNKlvAq2eWwh8mTh0h3cek6R4QcQYKpseNOUwc66Omo7w3VyKnEqmnzYnHqYH6SkyRPEs8Yiw5mRCSuYXQ8eqmVZuXRTpgRo1NqhuF6cVcNQ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mTDwuHB
-----END RSA PRIVATE KEY-----"""

def get_pay(out_trade_no, total_amount, return_url):
    """
    生成支付宝的支付链接
    :param out_trade_no: 商户订单号
    :param total_amount: 支付金额
    :param return_url: 支付成功后的回调URL地址
    :return: 支付宝支付页面URL
    """
    # 初始化支付宝SDK实例
    alipay = AliPay(
        # 自己的支付宝应用ID，沙箱环境的
        appid='9021000150625030',
        # 异步通知地址，None表示使用默认
        app_notify_url=None,
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        # 签名算法
        sign_type='RSA2'
    )

    # 生成支付宝页面支付请求参数
    order_string = alipay.api_alipay_trade_page_pay(
        # 商户的订单号，唯一，建议使用时间戳+随机数生成
        out_trade_no=out_trade_no,
        # 支付金额，转换为字符串主要是为了避免精度问题
        total_amount=str(total_amount),
        # 订单的标题
        subject='测试',
        # 支付成功后，同步回调地址
        return_url=return_url + "?t=" + out_trade_no,
        # 支付成功后的异步通知地址
        notify_url=return_url + "?t=" + out_trade_no,
    )
    # 拼接支付宝网关URL，生成一个可以访问的支付链接
    return "https://openapi-sandbox.dl.alipaydev.com/gateway.do?" + order_string